<script setup>

import axios from "axios";
import {onMounted, reactive, ref} from "vue";
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {useUserStore} from "@/stores/UserStore.js";


const route = useRoute();
const imgUrl = ref("../")
const showAllReplies = ref(false); // 默认不展开全部回复
const comment = reactive({
  getAll: [],
});

const getAllInn = reactive({
  getAllIn: []
})

function getAllIn() {
  axios.get("http://127.0.0.1:8081/art/getAllIn")
      .then((res) => {
        getAllInn.getAllIn = res.data;
        for (let item of getAllInn.getAllIn) {
          console.log(item.id);
        }
        console.log(getAllInn.getAllIn)
      })
      .catch((err) => {
        console.log(err);
      });
}

onMounted(() => {
  getAllIn()

})

function CommentAll() {
  axios
      .get("http://127.0.0.1:8081/comment/getAll")
      .then((res) => {
        comment.getAll = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
}

onMounted(() => {
  CommentAll();
});

const comments = reactive({
  getAll: {
    all: [],
  },
  getList: {
    qaq: [],
  },
});

const comentLike2 = ref(0); // 用于存储所有评论的点赞总数

function GetAllLike() {
  axios
      .get("http://127.0.0.1:8081/comment/getAllLike")
      .then((res) => {
        // 假设后端返回的是点赞总数的数值
        comentLike2.value = res.data; // 将点赞总数赋值给 comentLike
      })
      .catch((err) => {
        console.log(err);
      });
}

onMounted(() => {
  GetAllLike(); // 在组件加载时获取点赞总数
});

function CommentsList() {
  axios
      .get("http://127.0.0.1:8081/comments/getList")
      .then((res) => {
        comments.getAll.all = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
}

onMounted(() => {
  CommentsList();
  GetAllLike();
});

const article = reactive({
  getAll: {
    id: route.params.id,
    title: "",
    content: "",
    classificationID: null,
    topic: null,
    name: "", // 作者名
    count: null,
    like: null,
    collect: null,
    userAvatar: '',
    picPath: ''
  },
  getList: []
});

function Articel() {
  return axios.get(`http://127.0.0.1:8081/art/getAll/${article.getAll.id}`, {
    headers: {
      token: 'detail'
    }
  }).then(res => {
    article.getAll = res.data;
    console.log(res.data)
  }).catch(err => {
    console.log(err);
  });
}

// 在 onMounted 中使用 .then()
onMounted(() => {
  Articel()
  axios.post("http://127.0.0.1:8081/History/insert", {
    articleID: article.getAll.id,
    userID: useUserStore().getUserInfo.id
  }, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
});

const defaultPlaceholder = "参与讨论";
const inputValue = ref("");
const placeholderText = ref(defaultPlaceholder);

const clearPlaceholder = () => {
  if (inputValue.value === "") {
    placeholderText.value = "";
  }
};

const restorePlaceholder = () => {
  if (inputValue.value === "") {
    placeholderText.value = defaultPlaceholder;
  }
};
const commentadd = reactive({
  add: {
    content: '',
    id: 1
  }
})

function add() {
  if (!commentadd.add.content.trim()) {
    alert("评论内容不能为空"); // 如果内容为空，提示用户
    return;
  }

  axios.post("http://127.0.0.1:8081/comment/add", commentadd.add)
      .then(res => {
        if (res.data) {
          alert("评论成功"); // 使用 alert 提示用户
          commentadd.add.content = ""; // 清空输入框
          location.reload(); // 刷新页面
        } else {
          alert("评论失败，请重试");
        }
      })
      .catch(err => {
        console.log(err);
        alert("网络异常"); // 使用 alert 提示用户
      });
}

const commentCount = ref(0);


function getCommentCount() {
  axios.get("http://127.0.0.1:8081/comments/getResult")
      .then((res) => {
        commentCount.value = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
}

onMounted(() => {
  getCommentCount();
});

const showReplyBox = (commentId) => {
  // 这里可以根据 commentId 来决定显示哪个回复框
  // 例如，你可以使用一个 reactive 对象来存储每个评论的回复框状态
  replyBoxVisible.value = !replyBoxVisible.value;
};
const replyBoxVisible = ref(false); // 控制回复框的显示与隐藏
const replyContent = ref('');


const showSortOptions = ref(false); // 控制排序选项的显示与隐藏

const toggleSortOptions = () => {
  showSortOptions.value = !showSortOptions.value;
};

const comentLike = reactive({
  upda: {
    id: route.params.id,
    content: '',
    userID: 1,
    like: 1,
    time: ''
  }
})

function update(commentId) {
  comentLike.upda.id = commentId;
  axios.post(`http://127.0.0.1:8081/comment/update/${comentLike.upda.id}`, comentLike.upda, {
    headers: {token: "updat"}
  }).then(res => {
    if (res.data) {
      location.reload();//页面刷新
      router.push("/index")
    } else {
      alert("网络异常")
    }
  }).catch(err => {
    console.log(err); // 打印错误信息
    alert("请求失败，请检查网络或服务器状态");
  })
  return false
}

function goBack() {
  router.go(-1); // 后退一步
}

function goToPinLun() {
  router.push({name: 'PinLun'});
}

const getAllLike = reactive({
  getLike: []
})

function getLike() {
  axios
      .get("http://127.0.0.1:8081/comment/getLike")
      .then((res) => {
        getAllLike.getLike = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
}

onMounted(() => {
  getLike(); // 在组件加载时获取点赞总数

  console.log("postId:", commentData.getAdd.postId); // 打印 post_id
});


const commentData = reactive({
  getAdd: {
    userId: 1,
    content: '', // 评论内容
    postId: article.getAll.id,


  }
});

// 提交评论
function commentsAdd() {
  axios.post("http://127.0.0.1:8081/comments/add", commentData.getAdd)
      .then((res) => {
        if (res.data) {
          commentData.getAdd.content = ""; // 清空输入框
          replyBoxVisible.value = false; // 隐藏回复框
          CommentAll(); // 重新获取评论列表以更新显示
          location.reload()
        } else {
          alert("评论添加失败，请重试");
        }
      })
      .catch((err) => {
        console.log(err);
        a
        alert("网络异常，请稍后重试");
      });
}


</script>


<template>
  <div class = "mobile-home">
    <nav class = "navbar navbar-expand-lg t1">
      <ul class = "navbar-nav navbar">
        <li @click = "goBack"><img src = "../images/返回.png" height = "32" width = "32" /></li>
        <li class = "nav-item">
          <a class = "nav-link" href = "#">正文</a>

        </li>
        <li class = "nav-item">

          <a class = "nav-link" href = "#" @click.prevent = "goToPinLun">评论</a>
        </li>
        <li class = "nav-item float-right">
          <img src = "../images/上传.png" height = "32" width = "32" />
        </li>
      </ul>
    </nav>

    <div>


      <div class = "image-container">
        <img :src = "imgUrl+article.getAll.picPath" alt = "Article Image" />
      </div>

      <div class = "a2">
        <div class = "circle-container">
          <div class = "container">
            <div class = "circle">
              <img :src = "imgUrl+article.getAll.userAvatar" alt = "Article Image" />

            </div>

            <div class = "daihao">
              <p>{{ article.getAll.name }}</p>
              <div class = "lv7"><p>Lv.7</p></div>
            </div>
          </div>
          <div class = "guanzhu"><p>+关注</p></div>
        </div>
        <div>
          <div style = "margin-top: 5px; margin-bottom: 5px">
            <p style = "font-weight: bold">{{ article.getAll.title }}</p>
          </div>
          <p>{{ article.getAll.content }}</p>
        </div>
      </div>
      <div class = "biaoqian">
        <img src = "../images/井号.png" height = "20" width = "20" />
        <p>消失的光芒2</p>
      </div>
      <div>
        <div class = "pinlun">
          <p>评论</p>
          <div class = "remen" @click = "toggleSortOptions">
            <img src = "../images/sort.png" height = "32" width = "32" />
            <p>热门</p>
            <div id = "sortOptions" v-if = "showSortOptions">
              <p>热门</p>
              <p>正序</p>
              <p>倒叙</p>
            </div>
          </div>

        </div>

        <div v-for = "item in comment.getAll" :key = "item.id">
          <div class = "pj">
            <div class = "pinlun">
              <div class = "circle2">
                <img :src = "`${imgUrl}${item.userAvatar}`" width = "60" height = "60" />
              </div>
              <div class = "container">
                <p>{{ item.name }}</p>
                <div class = "lv8"><p>Lv.7</p></div>
              </div>
            </div>
            <div class = "dianzan" @click = "update(item.id)">
              <img src = "../images/点赞_块.png" height = "32" width = "32" />
              <p>{{ item.like }}</p>
            </div>
          </div>
          <div class = "plneirong">
            <p>{{ item.content }}</p>
          </div>
          <div class = "huifu">
            <!-- 显示前两条回复 -->
            <div class = "huifu2"
                 v-for = "(comments, index) in comments.getAll.all.slice(0, showAllReplies ? comments.getAll.all.length : 2)"
                 :key = "comments.id">
              <p @click = "showReplyBox(item.id)">{{ comments.name }} 回复 {{ item.name }}: {{ comments.content }}</p>
            </div>


            <div class = "reply-box" v-if = "replyBoxVisible">
              <input
                  type = "text"
                  v-model = "commentData.getAdd.content"
                  placeholder = "输入回复内容"
              />
              <button @click = "commentsAdd">提交</button>
            </div>


            <!-- 如果回复数量大于2，显示“全部回复”按钮 -->
            <div class = "quanbu" v-if = "comments.getAll.all.length > 2" @click = "showAllReplies = !showAllReplies">
              <img src = "../images/小三角.png" height = "16" width = "16" />
              <p>{{ showAllReplies ? '收起回复' : '全部回复' }}</p>
            </div>
          </div>
        </div>
      </div>

      <div class = "plk">
        <form @submit.prevent = "add" method = "post" class = "text-center">
          <input
              type = "text"
              v-model = "commentadd.add.content"
              :placeholder = "placeholderText"
              @focus = "clearPlaceholder"
              @blur = "restorePlaceholder"
              @keyup.enter = "add" /> <!-- 监听回车键 -->

        </form>

        <img src = "../images/点赞_块.png" height = "32" width = "32" />
        {{ comentLike2 }}
        <img src = "../images/收藏.png" height = "32" width = "32" />
        {{ article.getAll.collect }}
        <img src = "../images/评论2%20(1).png" height = "32" width = "32" />
        {{ commentCount }}
      </div>


    </div>
  </div>

</template>


<style scoped>
#sortOptions {
  margin-left: 60px;
  position: absolute;
  background-color: white;
  border: 1px solid #ccc;
  padding: 10px;
  margin-top: 10px;
}

.reply-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 10px;
  border-top: 1px solid #ccc;
  display: flex;
  justify-content: space-between;
}

.reply-box input {
  flex: 1;
  margin-right: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.reply-box button {
  padding: 5px 10px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

#sortOptions {
  position: absolute;
  background-color: white;
  border: 1px solid #ccc;
  padding: 10px;
  margin-left: 40px; /* 调整位置 */
}

.remen {
  display: flex;
  justify-content: center;
  align-items: center;
}

.plk {

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.daihao {
  display: flex;
}

.mobile-home {
  width: 430px;
  height: 932px;
  padding: 20px;

}


ul {
  list-style: none;
}

* {
  margin: 0;
  padding: 0;
}

.pj {
  display: flex;
  justify-content: space-between;
}

.quanbu {
  display: flex;
  justify-content: center;
  align-items: center;
}

.huifu {
  background-color: #f5f5f5;
  width: 100%;
  height: auto;
  margin-left: 10px;
}

.huifu2 p {
  padding: 10px;
  margin-left: 10px;
}

.image-container img {
  width: 100%;
  height: auto;
}

.navbar {
  display: flex;
  justify-content: space-around;
  width: 100%;
  padding: 0 10px;
}

.navbar-nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.nav-item {
  list-style: none;
}

.nav-link {
  text-decoration: none;
  color: black;

}

.image-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.circle {
  width: 50px;
  height: 50px;

  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden; /* Ensures the image doesn't overflow */
  margin-right: 10px;
}

.circle img {
  max-width: 100%;
  max-height: 100%;
}


.container {
  display: flex;
  padding: 10px;
  margin-top: -10px;
  align-items: center;
}

.lv7 {
  margin-left: 10px;
  background-color: #3498db;
  width: 40px;
  height: 20px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lv7 p {
  color: white;
}

.circle-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;

}

.guanzhu {
  margin-left: 10px;
  background-color: #000000;
  width: 60px;
  height: 30px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.guanzhu p {
  color: white;
}

.biaoqian {
  margin-top: 20px;
  background-color: #e3eef2;
  width: 120px;
  height: 30px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.biaoqian p {
  color: #6d92b1;
  margin-left: 5px;
}

.pinlun {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.circle2 {
  width: 50px;
  height: 50px;
  background-position: center center;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden; /* Ensures the image doesn't overflow */
  border-radius: 50%
}


.circle2 img {
  max-width: 100%;
  max-height: 100%;
}


.lv8 {
  margin-left: 10px;
  background-color: #3498db;
  width: 30px;
  height: 20px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lv8 p {
  color: white;
}

.dianzan {
  display: flex;
  margin: 5px;
  align-items: center;
  justify-content: center;
}

.plneirong {
  margin-top: 15px;
  margin-left: 10px;
}

.plneirong p {
  margin-top: -10px;
}

.plk input {
  margin-top: 10px;
  font-size: 1rem;
  height: 30px;
  border-radius: 5px;
  width: 200px;
}
</style>